package top.leoseven.adminproject.presenter;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;


import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Response;
import top.leoseven.adminproject.R;
import top.leoseven.adminproject.modle.AppInfo;
import top.leoseven.adminproject.modle.HomeWork;
import top.leoseven.adminproject.modle.KeCheng;
import top.leoseven.adminproject.modle.Student;
import top.leoseven.adminproject.service.MainService;

/**
 * Created by 10789 on 2018-02-21.
 */
public class MainPresenter {
    private MainService service;
    private Context mContext;
    private String tag=this.getClass().getSimpleName();
    public MainPresenter(MainService service, Context context){
        this.service=service;
        this.mContext=context;
    }
    public void initData(){
        OkHttpUtils.post(AppInfo.SERVER+mContext.getString(R.string.userinfo))
                .params("username",AppInfo.getUsername())
                .params("token",AppInfo.getToken())
                .execute(new UserInfoCallBack());
    }
    class UserInfoCallBack extends StringCallback {

        @Override
        public void onSuccess(String s, Call call, Response response) {
            Log.e(tag,s);
            JSONObject root = JSON.parseObject(s);
            ArrayList<Student> stus = new ArrayList<>();
            ArrayList<KeCheng> kcs = new ArrayList<>();
            ArrayList<HomeWork> works = new ArrayList<>();
            if (root.getIntValue("code")==200) {
                JSONArray stusarray = root.getJSONObject("data").getJSONArray("students");
                for (int i = 0; i < stusarray.size(); i++) {
                   stus.add( stusarray.getObject(i, Student.class));
                }
                JSONArray kcsarray = root.getJSONObject("data").getJSONArray("kechengs");
                for (int i = 0; i < kcsarray.size(); i++) {
                    kcs.add(kcsarray.getObject(i,KeCheng.class));
                }
                JSONArray hksarray = root.getJSONObject("data").getJSONArray("homeworks");
                for (int i = 0; i < hksarray.size(); i++) {
                    works.add(hksarray.getObject(i,HomeWork.class));
                }
            }
            service.onDataLoadFinish(stus,works,kcs);
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            service.onError(e.getMessage());
        }
    }
    public void distory(){
        mContext=null;
        service=null;
    }

}
